/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
import { DateModel } from '../types/date-model';
import { NameOfMonths } from '../types/month';
import { useDate } from './use-date';
import { useDateFormat } from './use-date-format';
import { DateObject, Period } from '../types/common';
import { UseDateModel } from './types';

export function useDateModel(): UseDateModel {

    const { getDate, getDate2, getEpocTime } = useDate();

    const { formatDate } = useDateFormat();

    function getDateModel(
        date: DateObject, period: Period, dateFormat: string,
        nameOfMonths: NameOfMonths, rangeDelimiter: string, returnFormat: string, dateStr = ''
    ): DateModel {

        const dateModel = date ? {
            date,
            jsDate: getDate2(date),
            formatted: dateStr.length ? dateStr : formatDate(date, dateFormat, nameOfMonths),
            returnFormatted: formatDate(date, returnFormat, nameOfMonths),
            epoc: getEpocTime(date)
        } : null;

        const periodModel = period ? {
            beginDate: period.from,
            beginJsDate: getDate(period.from),
            beginEpoc: getEpocTime(period.from),
            endDate: period.to,
            endJsDate: getDate(period.to),
            endEpoc: getEpocTime(period.to),
            formatted:
                formatDate(period.from, dateFormat, nameOfMonths) +
                rangeDelimiter +
                formatDate(period.to, dateFormat, nameOfMonths),
            returnFormatted:
                formatDate(period.from, returnFormat, nameOfMonths) +
                rangeDelimiter +
                formatDate(period.to, returnFormat, nameOfMonths),
        } : null;

        return {
            hasPeriod: periodModel !== null,
            date: dateModel,
            period: periodModel
        };
    }

    function getFormattedDate(model: DateModel): string | undefined {
        return !model.hasPeriod ? model.date?.formatted : model.period?.formatted;
    }

    return { getDateModel, getFormattedDate };
}
